package com.seari.tunnel.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jframe.util.HashPassword;
import com.seari.tunnel.entity.Role;
import com.seari.tunnel.entity.RolePage;
import com.seari.tunnel.entity.RoleParam;
import com.seari.tunnel.entity.User;
import com.seari.tunnel.entity.UserPage;
import com.seari.tunnel.service.IUserService;

@Controller
public class HomeController {
	private final String HOME_PAGE = "/home";
	private final String SET_PAGE = "/setting";
	private final String YHGL_PAGE = "/yhgl";
	
	private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Autowired
	IUserService userService;
	
	@RequestMapping(value="/home")
	public ModelAndView home(){
		
		return new ModelAndView(HOME_PAGE);
	}
	
	@RequiresRoles("admin")
	@RequestMapping(value="/setting")
	public ModelAndView setting(){
		
		return new ModelAndView(SET_PAGE);
	}
	
	@RequestMapping(value="/yhgl")
	public ModelAndView yhgl(){
		
		return new ModelAndView(YHGL_PAGE);
	}
	
	@RequestMapping(value = "/loadSecurityRoleSelect")
	@ResponseBody
	public Object getSecurityRoleSelect() {
		List<Role> data= userService.findSecurityRole();
		return data;
	}
	
	@RequestMapping(value = "/loadSecurityRole")
	@ResponseBody
	public Object getSecurityRole(@RequestParam("rows")int rows,@RequestParam("page")int page,@RequestParam(value="_search",required=false) boolean search,@RequestParam(value="searchString",required=false) String searchString) {
		RolePage pages = new RolePage();
		List<Role> data= userService.findSecurityRole();
		int rowCount = 0;
		if(data.size()%rows==0){
			rowCount = data.size()/rows;
		}else{
			rowCount = data.size()/rows+1;
		}
		List<Role> cdata = new ArrayList<Role>();
		for(int i=0;i<rows;i++){
			if(i+rows*(page-1)<data.size()){
			cdata.add(data.get(i+rows*(page-1)));
			}
		}
		pages.setPage(page);
		pages.setRecords(data.size());
		pages.setTotal(rowCount);
		pages.setRows(cdata);
		
		if(search==true){
			List<Role> searchdata=new ArrayList<Role>();
			try {
				searchString=new String(searchString.getBytes("ISO8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String str[]=searchString.split("&");
			for(int i=0;i<str.length;i++){
				searchdata.clear();
				for(Role sa:data){
					if(sa.getDescription().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getName().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}
				}
				data=new ArrayList<Role>(searchdata);
			}
			
			return searchdata;
		}
		return pages;
	}
	
	@RequestMapping(value = "/loadSecurityUser")
	@ResponseBody
	public Object getSecurityUser(@RequestParam("rows")int rows,@RequestParam("page")int page,@RequestParam(value="_search",required=false) boolean search,@RequestParam(value="searchString",required=false) String searchString) {
		UserPage pages = new UserPage();
		List<User> data= userService.findSecurityUser();
		int rowCount = 0;
		if(data.size()%rows==0){
			rowCount = data.size()/rows;
		}else{
			rowCount = data.size()/rows+1;
		}
		List<User> cdata = new ArrayList<User>();
		for(int i=0;i<rows;i++){
			if(i+rows*(page-1)<data.size()){
			cdata.add(data.get(i+rows*(page-1)));
			}
		}
		pages.setPage(page);
		pages.setRecords(data.size());
		pages.setTotal(rowCount);
		pages.setRows(cdata);
		
		if(search==true){
			List<User> searchdata=new ArrayList<User>();
			try {
				searchString=new String(searchString.getBytes("ISO8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String str[]=searchString.split("&");
			for(int i=0;i<str.length;i++){
				searchdata.clear();
				for(User sa:data){
					if(sa.getUsername().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getEmail().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getPhone().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}else if(sa.getRealname().indexOf(str[i])!=-1){
						searchdata.add(sa);
						continue;
					}
				}
				data=new ArrayList<User>(searchdata);
			}
			
			return searchdata;
		}
		return pages;
	}
	
	@RequestMapping(value="/securityRoleEdit")
	@ResponseBody
	public ModelAndView securityRoleEdit(@ModelAttribute RoleParam roleParam) throws Throwable{
	    if("add".equals(roleParam.getOper())){
	        Role role = new Role();
	        role.setDescription(roleParam.getDescription());
	        role.setName(roleParam.getName());
	        userService.addSecurityRole(role);
		}
		else if("edit".equals(roleParam.getOper())){
			Role role = new Role();
			role.setId(Long.parseLong(roleParam.getId()));
			role.setDescription(roleParam.getDescription());
	        role.setName(roleParam.getName());
	        userService.updateSecurityRole(role);
		}
		else{
			int id=0;
			if(roleParam.getId().contains(",")){
				id=Integer.parseInt(roleParam.getId().replace(',', ' ').trim());
			}else{
				id=Integer.parseInt(roleParam.getId());
			}
			userService.deleteSecurityRole(id);
		}
		return new ModelAndView(SET_PAGE);
	}
	
	@RequestMapping(value="/securityUserEdit")
	@ResponseBody
	public ModelAndView securityUserEdit(@ModelAttribute User user,@RequestParam("oper") String oper) throws Throwable{
		if("del".equals(oper.toString())){
	    userService.deleteSecurityUserById(user.getId().intValue());
		}else if("edit".equals(oper.toString())){
			userService.updateUser(user);
		}
		return new ModelAndView(YHGL_PAGE);
	}
	
	@RequestMapping(value="/addSecurityUser")
	@ResponseBody
	public ModelAndView addSecurityUser(@ModelAttribute User user) throws Throwable{
	    user.setCreateTime(sdf.format(new Date()));
	    HashPassword hashPassword = HashPassword.encryptPassword(user.getPlainPassword());
        user.setSalt(hashPassword.salt);
        user.setPassword(hashPassword.password);
        user.setComp(URLDecoder.decode(user.getComp(), "UTF-8"));
        user.setRealname(URLDecoder.decode(user.getRealname(), "UTF-8"));
        userService.addSecurityUser(user);
		return new ModelAndView(YHGL_PAGE);
	}
	
	@RequestMapping(value="/updateSecurityUserPassword")
	@ResponseBody
	public ModelAndView updateSecurityUser(@ModelAttribute User user) throws Throwable{
	    HashPassword hashPassword = HashPassword.encryptPassword(user.getPlainPassword());
        user.setSalt(hashPassword.salt);
        user.setPassword(hashPassword.password);
        userService.updateUserPassword(user);
		return new ModelAndView(YHGL_PAGE);
	}
}
